java_Java+Spring+MySql环境中安装和配置MyBatis的教程,1.MyBatis简介与配置MyBat
1.MyBatis简介与配置MyBatis+Spring+MySql
1.1MyBatis简介
MyBatis 是一个可以自定义SQL、存储过程和高级映射的持久层框架。MyBatis 摒除了大部分的JDBC代码、手工设置参数和结果集重获。MyBatis 只使用简单的XML 和注解来配置和映射基本数据类型、Map 接口和POJO 到数据库记录。相对Hibernate和Apache OJB等“一站式”ORM解决方案而言,Mybatis 是一种“半自动化”的ORM实现。
需要使用的Jar包:mybatis-3.0.2.jar(mybatis核心包)。mybatis-spring-1.0.0.jar(与Spring结合包)。
下载地址:
1.2MyBatis+Spring+MySql简单配置
1.2.1搭建Spring环境
(1)建立maven的web项目;
(2)加入Spring框架、配置文件;
(3)在pom.xml中加入所需要的jar包(spring框架的、mybatis、mybatis-spring、junit等);
(4)更改web.xml和spring的配置文件;
(5)添加一个jsp页面和对应的Controller;
(6)测试。
可参照:。使用Eclipse的Maven构建SpringMVC项目
1.2.2建立MySql数据库
建立一个学生选课管理数据库。
表:学生表、班级表、教师表、课程表、学生选课表。
逻辑关系:每个学生有一个班级;每个班级对应一个班主任教师;每个教师只能当一个班的班主任;
使用下面的sql进行建数据库,先建立学生表,插入数据(2条以上)。
更多sql请下载项目源文件,在resource/sql中。
/* 建立数据库 */ CREATE DATABASE STUDENT_MANAGER; USE STUDENT_MANAGER; /***** 建立student表 *****/ CREATE TABLE STUDENT_TBL ( STUDENT_ID VARCHAR(255) PRIMARY KEY, STUDENT_NAME VARCHAR(10) NOT NULL, STUDENT_SEX VARCHAR(10), STUDENT_BIRTHDAY DATE, CLASS_ID VARCHAR(255) ); /*插入学生数据*/ INSERT INTO STUDENT_TBL (STUDENT_ID, STUDENT_NAME, STUDENT_SEX, STUDENT_BIRTHDAY, CLASS_ID) VALUES (123456, '某某某', '女', '1980-08-01', 121546 )
创建连接MySql使用的配置文件mysql.properties。
jdbc.driverClassName=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/student_manager?user=root&password=limingnihao&useUnicode=true&characterEncoding=UTF-8
1.2.3搭建MyBatis环境
顺序随便,现在的顺序是因为可以尽量的少的修改写好的文件。
1.2.3.1创建实体类: StudentEntity
public class StudentEntity implements Serializable { private static final long serialVersionUID = 3096154202413606831L; private ClassEntity classEntity; private Date studentBirthday; private String studentID; private String studentName; private String studentSex; public ClassEntity getClassEntity() { return classEntity; } public Date getStudentBirthday() { return studentBirthday; } public String getStudentID() { return studentID; } public String getStudentName() { return studentName; } public String getStudentSex() { return studentSex; } public void setClassEntity(ClassEntity classEntity) { this.classEntity = classEntity; } public void setStudentBirthday(Date studentBirthday) { this.studentBirthday = studentBirthday; } public void setStudentID(String studentID) { this.studentID = studentID; } public void setStudentName(String studentName) { this.studentName = studentName; } public void setStudentSex(String studentSex) { this.studentSex = studentSex; } }
1.2.3.2创建数据访问接口
Student类对应的dao接口:StudentMapper。
public interface StudentMapper { public StudentEntity getStudent(String studentID); public StudentEntity getStudentAndClass(String studentID); public List<StudentEntity> getStudentAll(); public void insertStudent(StudentEntity entity); public void deleteStudent(StudentEntity entity); public void updateStudent(StudentEntity entity); }
1.2.3.3创建SQL映射语句文件
Student类的sql语句文件StudentMapper.xml
resultMap标签:表字段与属性的映射。
Select标签:查询sql。
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.manager.data.StudentMapper"> <resultMap type="StudentEntity"> <id property="studentID" column="STUDENT_ID"/> <result property="studentName" column="STUDENT_NAME"/> <result property="studentSex" column="STUDENT_SEX"/> <result property="studentBirthday" column="STUDENT_BIRTHDAY"/> </resultMap> <!-- 查询学生,根据id --> <select parameterType="String" resultType="StudentEntity" resultMap="studentResultMap"> <![CDATA[ SELECT * from STUDENT_TBL ST WHERE ST.STUDENT_ID = #{studentID} ]]> </select> <!-- 查询学生列表 --> <select resultType="com.manager.data.model.StudentEntity" resultMap="studentResultMap"> <![CDATA[ SELECT * from STUDENT_TBL ]]> </select> </mapper>
1.2.3.4创建MyBatis的mapper配置文件
在src/main/resource中创建MyBatis配置文件:mybatis-config.xml。
typeAliases标签:给类起一个别名。com.manager.data.model.StudentEntity类,可以使用StudentEntity代替。
Mappers标签:加载MyBatis中实体类的SQL映射语句文件。
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <typeAliases> <typeAlias alias="StudentEntity" type="com.manager.data.model.StudentEntity"/> </typeAliases> <mappers> <mapper resource="com/manager/data/maps/StudentMapper.xml" /> </mappers> </configuration>
1.2.3.5修改Spring 的配置文件
主要是添加SqlSession的制作工厂类的bean:SqlSessionFactoryBean,(在mybatis.spring包中)。需要指定配置文件位置和dataSource。
和数据访问接口对应的实现bean。通过MapperFactoryBean创建出来。需要执行接口类全称和SqlSession工厂bean的引用。
<!-- 导入属性配置文件 --> <context:property-placeholder location="classpath:mysql.properties" /> <bean> <property value="${jdbc.driverClassName}" /> <property value="${jdbc.url}" /> </bean> <bean> <property ref="dataSource" /> </bean> <bean> <property value="classpath:mybatis-config.xml" /> <property ref="dataSource" /> </bean> <!— mapper bean --> <bean> <property value="com.manager.data.StudentMapper" /> <property ref="sqlSessionFactory" /> </bean>
也可以不定义mapper的bean,使用注解:
将StudentMapper加入注解
@Repository @Transactional public interface StudentMapper { }
对应的需要在dispatcher-servlet.xml中加入扫描:
<bean> <property value="org.springframework.stereotype.Repository"/> <property value="com.liming.manager"/> <property ref="sqlSessionFactory"/> </bean>
1.2.4测试StudentMapper
使用SpringMVC测试,创建一个TestController,配置tomcat,访问index.do页面进行测试:
@Controller public class TestController { @Autowired private StudentMapper studentMapper; @RequestMapping(value = "index.do") public void indexPage() { StudentEntity entity = studentMapper.getStudent("10000013"); System.out.println("name:" + entity.getStudentName()); } }
使用Junit测试:
@RunWith(value = SpringJUnit4ClassRunner.class) @ContextConfiguration(value = "test-servlet.xml") public class StudentMapperTest { @Autowired private ClassMapper classMapper; @Autowired private StudentMapper studentMapper; @Transactional public void getStudentTest(){ StudentEntity entity = studentMapper.getStudent("10000013"); System.out.println("" + entity.getStudentID() + entity.getStudentName()); List<StudentEntity> studentList = studentMapper.getStudentAll(); for( StudentEntity entityTemp : studentList){ System.out.println(entityTemp.getStudentName()); } } }
2.MyBatis的主配置文件
在定义sqlSessionFactory时需要指定MyBatis主配置文件:
<bean> <property value="classpath:mybatis-config.xml" /> <property ref="dataSource" /> </bean>
MyBatis配置文件中大标签configuration下子标签包括:
configuration |--- properties |--- settings |--- typeAliases |--- typeHandlers |--- objectFactory |--- plugins |--- environments |--- |--- environment |--- |--- |--- transactionManager |--- |--- |__ dataSource |__ mappers
2.1 properties属性
properties和java的.properties的配置文件有关。配置properties的resource指定.properties的路径,然后再在properties标签下配置property的name和value,则可以替换.properties文件中相应属性值。
<!-- 属性替换 --> <properties resource="mysql.properties"> <property value="com.mysql.jdbc.Driver"/> <property value="jdbc:mysql://localhost:3306/student_manager"/> <property value="root"/> <property value="limingnihao"/> </properties>
设置项 描述 允许值 默认值 cacheEnabled 对在此配置文件下的所有cache 进行全局性开/关设置。 true | false true lazyLoadingEnabled 全局性设置懒加载。如果设为‘false',则所有相关联的都会被初始化加载。 true | false true aggressiveLazyLoading 当设置为‘true'的时候,懒加载的对象可能被任何懒属性全部加载。否则,每个属性都按需加载。 true | false true multipleResultSetsEnabled 允许和不允许单条语句返回多个数据集(取决于驱动需求) true | false true useColumnLabel 使用列标签代替列名称。不同的驱动器有不同的作法。参考一下驱动器文档,或者用这两个不同的选项进行测试一下。 true | false true useGeneratedKeys 允许JDBC 生成主键。需要驱动器支持。如果设为了true,这个设置将强制使用被生成的主键,有一些驱动器不兼容不过仍然可以执行。 true | false false autoMappingBehavior 指定MyBatis 是否并且如何来自动映射数据表字段与对象的属性。PARTIAL将只自动映射简单的,没有嵌套的结果。FULL 将自动映射所有复杂的结果。 NONE, PARTIAL, FULL PARTIAL defaultExecutorType 配置和设定执行器,SIMPLE 执行器执行其它语句。REUSE 执行器可能重复使用prepared statements 语句,BATCH执行器可以重复执行语句和批量更新。 SIMPLE REUSE BATCH SIMPLE defaultStatementTimeout 设置一个时限,以决定让驱动器等待数据库回应的多长时间为超时 正整数 Not Set (null)
2.2 settings设置
这是MyBatis 修改操作运行过程细节的重要的步骤。下方这个表格描述了这些设置项、含义和默认值。
例如:
<settings> <setting value="true" /> <setting value="true" /> <setting value="true" /> <setting value="true" /> <setting value="false" /> <setting value="false" /> <setting value="SIMPLE" /> </settings>
2.3 typeAliases类型别名
类型别名是Java 类型的简称。
它仅仅只是关联到XML 配置,简写冗长的JAVA 类名。例如:
<typeAliases> <typeAlias alias="UserEntity" type="com.manager.data.model.UserEntity" /> <typeAlias alias="StudentEntity" type="com.manager.data.model.StudentEntity" /> <typeAlias alias="ClassEntity" type="com.manager.data.model.ClassEntity" /> </typeAliases>
使用这个配置,“StudentEntity”就能在任何地方代替“com.manager.data.model.StudentEntity”被使用。 别名 映射的类型 _byte byte _long long _short short _int int _integer int _double double _float float _boolean boolean string String byte Byte long Long short Short int Integer integer Integer double Double float Float boolean Boolean date Date decimal BigDecimal bigdecimal BigDecimal object Object map Map hashmap HashMap list List arraylist ArrayList collection Collection iterator Iterator
对于普通的Java类型,有许多内建的类型别名。它们都是大小写不敏感的,由于重载的名字,要注意原生类型的特殊处理。
2.4 typeHandlers类型句柄 类型处理器 Java类型 JDBC类型 BooleanTypeHandler Boolean,boolean 任何兼容的布尔值 ByteTypeHandler Byte,byte 任何兼容的数字或字节类型 ShortTypeHandler Short,short 任何兼容的数字或短整型 IntegerTypeHandler Integer,int 任何兼容的数字和整型 LongTypeHandler Long,long 任何兼容的数字或长整型 FloatTypeHandler Float,float 任何兼容的数字或单精度浮点型 DoubleTypeHandler Double,double 任何兼容的数字或双精度浮点型 BigDecimalTypeHandler BigDecimal 任何兼容的数字或十进制小数类型 StringTypeHandler String CHAR和VARCHAR类型 ClobTypeHandler String CLOB和LONGVARCHAR类型 NStringTypeHandler String NVARCHAR和NCHAR类型 NClobTypeHandler String NCLOB类型 ByteArrayTypeHandler byte[] 任何兼容的字节流类型 BlobTypeHandler byte[] BLOB和LONGVARBINARY类型 DateTypeHandler Date(java.util) TIMESTAMP类型 DateOnlyTypeHandler Date(java.util) DATE类型 TimeOnlyTypeHandler Date(java.util) TIME类型 SqlTimestampTypeHandler Timestamp(java.sql) TIMESTAMP类型 SqlDateTypeHandler Date(java.sql) DATE类型 SqlTimeTypeHandler Time(java.sql) TIME类型 ObjectTypeHandler Any 其他或未指定类型 EnumTypeHandler Enumeration类型 VARCHAR-任何兼容的字符串类型,作为代码存储(而不是索引)。
无论是MyBatis在预处理语句中设置一个参数,还是从结果集中取出一个值时,类型处理器被用来将获取的值以合适的方式转换成Java类型。下面这个表格描述了默认的类型处理器。
你可以重写类型处理器或创建你自己的类型处理器来处理不支持的或非标准的类型。要这样做的话,简单实现TypeHandler接口(org.mybatis.type),然后映射新的类型处理器类到Java类型,还有可选的一个JDBC类型。然后再typeHandlers中添加这个类型处理器。
新定义的类型处理器将会覆盖已经存在的处理Java的String类型属性和VARCHAR参数及结果的类型处理器。要注意MyBatis不会审视数据库元信息来决定使用哪种类型,所以你必须在参数和结果映射中指定那是VARCHAR类型的字段,来绑定到正确的类型处理器上。这是因为MyBatis直到语句被执行都不知道数据类型的这个现实导致的。
public class LimingStringTypeHandler implements TypeHandler { @Override public void setParameter(PreparedStatement ps, int i, Object parameter, JdbcType jdbcType) throws SQLException { System.out.println("setParameter - parameter: " + ((String) parameter) + ", jdbcType: " + jdbcType.TYPE_CODE); ps.setString(i, ((String) parameter)); } @Override public Object getResult(ResultSet rs, String columnName) throws SQLException { System.out.println("getResult - columnName: " + columnName); return rs.getString(columnName); } @Override public Object getResult(CallableStatement cs, int columnIndex) throws SQLException { System.out.println("getResult - columnIndex: " + columnIndex); return cs.getString(columnIndex); } }
在配置文件的typeHandlers中添加typeHandler标签。
<typeHandlers> <typeHandler javaType="String" jdbcType="VARCHAR" handler="liming.student.manager.type.LimingStringTypeHandler"/> </typeHandlers>
2.5 ObjectFactory对象工厂
每次MyBatis 为结果对象创建一个新实例,都会用到ObjectFactory。默认的ObjectFactory 与使用目标类的构造函数创建一个实例毫无区别,如果有已经映射的参数,那也可能使用带参数的构造函数。
如果你重写ObjectFactory 的默认操作,你可以通过继承org.apache.ibatis.reflection.factory.DefaultObjectFactory创建一下你自己的。
ObjectFactory接口很简单。它包含两个创建用的方法,一个是处理默认构造方法的,另外一个是处理带参数构造方法的。最终,setProperties方法可以被用来配置ObjectFactory。在初始化你的ObjectFactory实例后,objectFactory元素体中定义的属性会被传递给setProperties方法。
相关热词:
本站内容来源于网络,如有侵权请与我们联系,我们会及时删除,我们深感抱歉!
注:本站所有信息仅供用于网络技术学习参考,学习中请遵循相关法律法规!
本文地址: https://v30.fanwenzhu.com/jiaob/java/10178.shtml
相关文章
热门TAG
win10 ecshop 主机 阿里云 解决 配置 C# C++ 解析 SQL语句 命令 Go语言 方法 CSS3 HTML5 CSS win7 MSSQL 服务器配置 IIS7.5 IIS7 IIS6 IIS CentOS 7 Linux oracle数据库 oracle phpcms discuz discuz教程最新文章
-
Fitness fitness){ /*double X1=m
时间:2021-01-21
-
所以这里也是需要注意的
时间:2021-01-21
-
hadoop上传文件成果实例代
时间:2021-01-15
-
hadoop负责按key值将map的输
时间:2021-01-15
-
记得勾选springconfig.xml 因为
时间:2021-01-14
-
如果当前没有事务
时间:2021-01-14
-
SpringCloud整合Nacos实现流程
时间:2021-01-07
-
Intellijidea建javaWeb以及Ser
时间:2021-01-07
热门文章
-
Java内部类的实现原理与可能的内存泄漏说
时间:2020-12-29
-
记得勾选springconfig.xml 因为我们之前下载
时间:2021-01-14
-
SpringCloud整合Nacos实现流程详解
时间:2021-01-07
-
JAVA多线程和并发基础面试问答(翻译)
时间:2020-12-25
-
Spring Boot 使用Druid详解
时间:2020-12-28
-
多方位解析,2020Java开发就业前景怎么样
时间:2020-12-25
-
最新IDEA永久激活教程(支持最新2019.2版本
时间:2020-12-25
-
Fitness fitness){ /*double X1=min+0.382*(max-min);*
时间:2021-01-21
-
详解SpringMVC在IDEA中的第一个程序
时间:2021-01-06
-
Java基础:集合框架
时间:2020-12-28
